<template>
  <div v-loading="infoLoading && inventoryId" :class="{'mobile-create': showMobilePage}" class="create-page-container">
    <Title title="库存信息" style="margin-bottom:16px" font-size="16px" />
    <el-form ref="projectForm" :model="projectForm" :rules="projectRules" :label-position="formAlign" class="lineHeight32" label-width="80px">
      <el-row type="flex" class="response-el-row">
        <el-col :span="12" class="responsive-col-lg-8">
          <el-form-item label="标题" prop="title">
            <el-input v-model.trim="projectForm.title" name="title" type="text" placeholder="不超过200个字符" size="small" maxlength="200" style="width: 220px" />
          </el-form-item>
        </el-col>
        <el-col :span="12" class="responsive-col-lg-8">
          <el-form-item label="IP形象" prop="IP">
            <el-select
              v-loadmore="userLoadMore"
              ref="projectFormIP"
              v-model="projectForm.IP"
              :filter-method="filterData"
              popper-class="global-select-down"
              name="ipOperator"
              filterable
              collapse-tags
              size="small"
              clearable
              value-key="ipId"
              style="width: 220px;"
              class="remoteRequestClient"
              @change="ipChange" >
              <el-option
                v-if="defaultIpOption.ipId"
                :label="`${defaultIpOption.ipName || '--'}/${defaultIpOption.ipSeriesName || '--'}`"
                :value="defaultIpOption" />
              <el-option
                v-for="(item, index) in IPOption.items"
                :key="index"
                :label="`${item.ipName || '--'}/${item.ipSeriesName || '--'}`"
                :value="item" />
              <div v-if="userLoading" class="loading-container"><i class="el-icon-loading"/></div>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12" class="responsive-col-lg-8">
          <el-form-item label="商品属性" prop="type">
            <el-input v-model.trim="projectForm.type" name="type" placeholder="" type="text" size="small" maxlength="50" style="width: 220px" />
          </el-form-item>
        </el-col>
        <el-col :span="12" class="responsive-col-lg-8">
          <el-form-item label="SKU编码" prop="code">
            <el-input
              :disabled="exceedsMonthStatus"
              v-model.trim="projectForm.code"
              name="code"
              placeholder=""
              type="text"
              size="small"
              maxlength="50"
              style="width: 220px" />
          </el-form-item>
        </el-col>
        <el-col :span="12" class="responsive-col-lg-8">
          <el-form-item label="仓库" prop="repository">
            <selectWithUserLoad
              ref="selectUser"
              v-model="projectForm.repository"
              :hide-select-list="projectForm.repository && JSON.stringify(projectForm.repository) !== '{}' ?[projectForm.repository] : []"
              :select-data-list="projectForm.repository ?[projectForm.repository] : []"
              :multiple="false"
              :loadmore-method="getRepository()"
              :disabled="exceedsMonthStatus"
              :class="{'width220': !showMobilePage}"
              placeholder="请选择仓库"
              extend-class="create-supplier-order-select"
              value-type="object"
              key-name="repositoryId"
              label-name="repositoryName"
              filterable
              collapse-tags
              @change="repositoryChange"
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <fixed-pagination>
      <div class="center">
        <el-button v-if="hasRouteAuth(inventoryId ? 'mengli:inventory:edit' : 'mengli:inventory:add')" :loading="loading" type="primary" size="small" @click="toSave('projectForm')">{{ inventoryId ? '保存' : '创建' }}</el-button>
        <el-button type="info" size="small" class="cancel-btn-style" @click="toClear">取消</el-button>
      </div>
    </fixed-pagination>
  </div>
</template>
<script>
import selectWithUserLoad from '@/components/Common/selectWithUserLoad';
import Title from '@/components/Title';
import { getInventoryRepo, getmengliIpList, createInventory, editInventory, getInventoryDetail } from '@/api/mengli';
import { hasRouteAuth } from '@/utils/permission';
import mobileCreate from '@/mixins/mobileCreate';

export default {
  components: {
    Title,
    selectWithUserLoad
  },
  mixins: [mobileCreate],
  data() {
    const validateCN = (rule, value, callback) => {
      const reg = new RegExp('[\u4E00-\u9FFF]+$');
      if (reg.test(value)) {
        callback(new Error('不支持中文字符'));
      } else {
        callback();
      }
    };
    return {
      projectForm: {
        title: '',
        IP: null,
        code: null,
        type: null,
        repository: null,
        repositoryName: null,
        repositoryId: null
      },
      projectRules: {
        title: [{ required: true, trigger: 'change', message: '请填写标题' }],
        IP: [{ required: true, trigger: 'change', message: '请选择IP形象' }],
        code: [
          { required: true, trigger: 'change', message: '请填写入SKU编码' },
          { validator: validateCN, trigger: 'change' }
        ],
        type: [{ required: true, trigger: 'change', message: '请填写商品属性' }],
        repository: [{ required: true, trigger: 'change', message: '请选择仓库' }]
      },
      IPOption: {
        items: [],
        total: 0
      },
      defaultIpOption: {},
      loading: false,
      inventoryId: null,
      page: 1,
      perPage: 15,
      userLoading: false,
      // catchQuery: null,
      infoLoading: false,
      exceedsMonthStatus: false
    };
  },
  mounted() {
    window.remoteRequest('.remoteRequestClient', this.filterData);
  },
  created() {
    this.inventoryId = this.$route.params.id || '';
    if (this.inventoryId) {
      this.getInfo();
    } else {
      this.getmengliIpList();
    }
  },
  methods: {
    hasRouteAuth,
    repositoryChange(item) {
      this.projectForm.repositoryName = item.repositoryName;
      this.projectForm.repositoryId = item.repositoryId;
    },
    getRepository() {
      const a = function(params) {
        return new Promise((resolve, reject) => {
          params.repositoryName = '';
          if (params.userName) params.repositoryName = params.userName;
          delete params.userName;
          getInventoryRepo(params).then(res => {
            resolve(res);
          }).catch(err => {
            reject(err);
          });
        });
      };
      return a;
    },
    userLoadMore() {
      const ipList = this.IPOption;
      this.page = ipList.page;
      if (ipList.items) {
        if (ipList.items.length < ipList.total - (_.isEmpty(this.defaultIpOption) ? 0 : 1) && !this.userLoading) {
          this.page += 1;
          this.getmengliIpList(this.page);
        }
      }
    },
    filterData(val) {
      this.getmengliIpList(1, val);
    },
    // ip列表
    async getmengliIpList(page = 1, query = null) {
      // query && (this.catchQuery = query);
      this.userLoading = true;
      try {
        const { perPage } = this;
        const params = {
          page,
          perPage,
          needPermissions: 0,
          keyword: query
        };
        const { data, code } = await getmengliIpList(params);
        this.userLoading = false;
        if (code === 200) {
          this.spliceDefault(data.items);
          if (page > 1 && this.IPOption.items && this.IPOption.items.length > 0) {
            const concatList = this.IPOption.items.concat(data.items);
            data.items = concatList;
            this.IPOption = data;
          } else {
            this.IPOption = data;
          }
        }
      } catch (error) {
        this.userLoading = false;
      }
    },
    spliceDefault(list) {
      if (!Array.isArray(list) || !list.length || !this.defaultIpOption.ipId) return;
      const index = list.findIndex(item => item.ipId === this.defaultIpOption.ipId);
      return index > -1 ? list.splice(index, 1) : list;
    },
    ipChange(val) {
      if (!val) {
        this.getmengliIpList(1, val);
        this.defaultIpOption = {};
      }
      this.$forceUpdate();
    },
    getInfo() {
      this.infoLoading = true;
      getInventoryDetail(this.inventoryId).then(res => {
        this.infoLoading = false;
        this.projectForm = res.data;
        this.exceedsMonthStatus = this.validStockInTime(res.data.createTime);
        const { ipId, ipName, ipSeriesName } = this.projectForm;
        this.getmengliIpList();
        if (ipId) {
          this.defaultIpOption = { ipId, ipName, ipSeriesName };
          this.projectForm.IP = { ipId, ipName, ipSeriesName };
        }
      }).catch(err => {
        console.log(err);
        this.infoLoading = false;
        this.$message.error(err.message);
      });
    },
    validStockInTime(date) {
      if (!date) return false;
      const now = new Date();
      const year = now.getFullYear();
      const month = now.getMonth();
      // 截止操作日期至上个月
      const deadline = new Date(year, month - 1, 1, 0, 0, 0).getTime();
      return date < deadline;
    },
    toAdd(params) {
      createInventory(params).then(res => {
        this.loading = false;
        if (res.code === 200) {
          this.$message.success('新建成功');
          this.$router.push({
            name: 'mengliInventory'
          });
        } else if (res.code === 501) {
          this.$message.error(res.message);
        }
      }, result => {
        this.loading = false;
      });
    },
    toEdit(params) {
      editInventory(this.inventoryId, params).then(res => {
        this.loading = false;
        if (res.code === 200) {
          this.$message.success('修改成功');
          this.$router.push({
            name: 'mengliInventory'
          });
        } else if (res.code === 501) {
          this.$message.error(res.message);
        }
      }, result => {
        this.loading = false;
      });
    },
    toSave(formValue) {
      this.$refs[formValue].validate((vaild) => {
        if (vaild) {
          const params = {
            ...this.projectForm
          };
          if (this.projectForm.IP) {
            params.ipId = this.projectForm.IP.ipId;
            params.ipName = this.projectForm.IP.ipName;
            params.ipSeriesName = this.projectForm.IP.ipSeriesName;
          } else {
            params.ipId = '';
            params.ipName = '';
            params.ipSeriesName = '';
          }
          this.loading = true;
          if (this.inventoryId) {
            this.toEdit(params);
          } else {
            this.toAdd(params);
          }
        } else {
          this.loading = false;
          return false;
        }
      });
    },
    toClear() {
      this.$router.push({
        name: 'mengliInventory'
      });
    }
  }
};
</script>
<style lang="scss" scoped>
.create-page-container{
  &::v-deep {
    .el-form-item{
      margin-bottom: 24px;
    }
  }
}
.loading-container {
  width: 100%;
  text-align: center;
  i {
    color: #999;
  }
}
.width220 {
  width: 220px;
  ::v-deep .el-input__inner {
    width: 220px;
  }
}
</style>
